<!-- Template -->
<template>
  <div class="add-role">
    <!-- 头部 -->
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()">
          <i class="el-icon-arrow-left" />返回</span
        >
        <span>|</span>
        <span>编辑角色</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>

    <!-- 主体 -->
    <main class="add-main">
      <!-- 步骤容器 -->
      <div class="step-container">
        <el-steps
          direction="vertical"
          :active="activeStep"
          finish-status="success"
        >
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>

      <!-- 表单容器 -->
      <div class="form-container" v-show="activeStep === 1">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form
            class="form-box"
            ref="roleForm"
            :model="roleForm"
            :rules="roleRules"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>

            <el-form-item label="角色描述">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 权限配置 -->
      <div class="form-container" v-show="activeStep === 2">
        <div class="title">权限配置</div>
        <div class="tree-wrapper">
          <div v-for="item in treeList" :key="item.id" class="tree-item">
            <div class="tree-title">{{ item.title }}</div>
            <el-tree
              ref="tree"
              :key="item.id"
              :data="item.children"
              show-checkbox
              default-expand-all
              node-key="id"
              highlight-current
              :props="{ label: 'title' }"
              check-strictly
            />
          </div>
        </div>
      </div>

      <!-- 检查并完成 -->
      <div class="form-container" v-show="activeStep === 3">
        <div class="title">检查并完成</div>
        <div class="info">
          <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
          <div class="form-item">角色描述：{{ roleForm.remark }}</div>
          <div class="form-item">角色权限：</div>
          <div class="tree-wrapper">
            <div
              v-for="item in disableTreeList"
              :key="item.id"
              class="tree-item"
            >
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="diabledTree"
                :key="item.id"
                :data="item.children"
                show-checkbox
                default-expand-all
                node-key="id"
                :highlight-current="false"
                :props="{ label: 'title' }"
                check-strictly
              />
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部 -->
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="pres" v-if="activeStep > 1">上一步</el-button>
        <el-button type="primary" @click="next" v-if="activeStep < 3"
          >下一步</el-button
        >
        <el-button v-if="activeStep === 3" type="primary" @click="EditRoleData"
          >确认修改</el-button
        >
      </div>
    </footer>
  </div>
</template>

<!-- Script -->
<script>
import {
  getTreeListAPI,
  updateRoleAPI,
  getRoleTreeDetail,
} from "@/api/permiss";

function setDisabled(treeList) {
  if (treeList) {
    treeList.forEach((item) => {
      item.disabled = true;
      // 递归处理
      if (item.children) {
        setDisabled(item.children);
      }
    });
  }
}

export default {
  data() {
    return {
      activeStep: 1, // 当前步骤
      treeList: [], // 权限树数据
      disableTreeList: [], // 禁用的权限树数据
      roleForm: {
        roleName: "", // 角色名称
        remark: "", // 角色描述
        roleId: "", // 角色ID
        perms: [], // 权限点
      },
      roleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    // 初始化加载数据
    this.getTreeList();
    if (this.$route.query.id) {
      this.getRoleDetail();
    }
  },
  methods: {
    async getTreeList() {
      // 获取权限树列表
      const res = await getTreeListAPI();
      this.treeList = res.data;
      this.disableTreeList = JSON.parse(JSON.stringify(this.treeList));
      setDisabled(this.disableTreeList);
    },
    async EditRoleData() {
      // 提交编辑角色数据
      try {
        let res = await updateRoleAPI(this.roleForm);
        this.$message.success(res.msg);
        this.$router.push("/sys/role");
      } catch (error) {
        this.$message.error("修改角色失败，请稍后再试");
      }
    },
    async getRoleDetail() {
      // 获取角色详情
      const id = this.$route.query.id;
      const res = await getRoleTreeDetail(id);
      const { perms, remark, roleId, roleName } = res.data;
      // 打印数据
      console.log(perms, remark, roleId, roleName);
      // 回填表单数据
      this.roleForm = { perms, remark, roleId, roleName };
      // 回填权限树
      if (this.$refs.tree && Array.isArray(this.$refs.tree)) {
        this.$refs.tree.forEach((tree, index) => {
          tree.setCheckedKeys(this.roleForm.perms[index]);
        })
      }
    },
    pres() {
      // 上一步操作
      if (this.activeStep-- <= 1) this.activeStep = 1;
    },
    next() {
      // 下一步操作
      if (this.activeStep === 1) {
        // 校验表单
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            this.activeStep++;
          }
        });
      } else if (this.activeStep === 2) {
        // 处理权限数据
        this.roleForm.perms = [];
        if (this.$refs.tree) {
          this.$refs.tree.forEach((tree) => {
            this.roleForm.perms.push(tree.getCheckedKeys());
          });

          if (this.roleForm.perms.flat().length === 0) {
            this.$message({
              type: "error",
              message: "请至少选择一个权限点",
            });
          } else {
            this.activeStep++;
            if (this.$refs.diabledTree) {
              this.$refs.diabledTree.forEach((tree, index) => {
                tree.setCheckedKeys(this.roleForm.perms[index]);
              });
            }
          }
        }
      }
    },
  },
};
</script>

<!-- Style -->
<style scoped lang="scss">
::v-deep .el-tree-node__content label.el-checkbox.is-checked {
  span.is-checked .el-checkbox__inner {
    background-color: #0094ff;
  }
}

.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info {
          font-size: 14px;
          color: #666;
          .form-item {
            margin-bottom: 20px;
          }
        }
      }
      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
}

.tree-wrapper {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;

  .tree-item {
    flex: 1;
    padding: 0px 4px;
    text-align: center;

    .tree-title {
      background: #f5f7fa;
      text-align: center;
      padding: 10px 0;
      margin-bottom: 12px;
    }
  }
}
</style>
